<template>
  <div class="register-container">
    <!-- 用户协议弹窗组件 -->
    <agreement ref="agreementModal" @agree="onAgree" />
 
    <div class="register-card">
      <h2 class="register-title">客户注册</h2>
 
      <!-- 步骤指示器（保持原有样式） -->
      <el-steps :active="activeStep" finish-status="success" simple class="custom-steps">
        <el-step title="基本信息" />
        <el-step title="账号安全" />
      </el-steps>
 
      <!-- 第一步表单 -->
      <el-form 
        v-if="activeStep === 1"
        :model="form"
        class="register-form"
        label-position="top"
        :rules="step1Rules"
        ref="step1Form"
      >
        <div class="info-row">
          <el-form-item label="用户名" prop="name" class="info-item">
            <el-input 
              v-model="form.name"     
              placeholder="请输入姓名"
              prefix-icon="User"
              clearable 
            />
          </el-form-item>
          
          <el-form-item label="手机号" prop="phone" class="info-item">
            <el-input 
              v-model="form.phone"     
              placeholder="请输入11位手机号"
              maxlength="11"
              prefix-icon="Iphone"
              clearable 
            />
          </el-form-item>
        </div>
 
        <el-form-item label="公司全名" prop="company">
          <el-input 
            v-model="form.company"     
            placeholder="请输入公司全名"
            prefix-icon="House"
            clearable 
          />
        </el-form-item>
 
        <el-form-item label="收货地址" prop="address">
          <el-input 
            v-model="form.address"    
            type="textarea"
            :rows="3"
            placeholder="请输入详细送货地址：省/市/区(县)/详细"
            prefix-icon="Location"
          />
        </el-form-item>
 
        <el-button 
          type="primary"
          @click="nextStep"
          class="register-btn"
        >
          下一步 
        </el-button>
      </el-form>
 
      <!-- 第二步表单 -->
      <el-form 
        v-if="activeStep === 2"
        :model="form"
        class="register-form"
        label-position="top"
        :rules="step2Rules"
        ref="step2Form"
      >
        <div class="password-address-row">
          <div class="password-column">
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="form.password"     
                type="password"
                placeholder="请输入密码"
                prefix-icon="Lock"
                show-password 
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="uiState.confirmPassword"   
                type="password"
                placeholder="请再次输入密码"
                prefix-icon="Lock"
                show-password 
              />
            </el-form-item>
          </div>
        </div>
 
        <div class="email-row">
          <el-form-item label="邮箱" prop="email" class="email-input">
            <el-input 
              v-model="form.email"  
              placeholder="请输入工作邮箱"
              prefix-icon="Message"
              clearable 
            />
          </el-form-item>
          
          <el-form-item class="code-btn">
            <el-button 
              type="primary" 
              plain 
              @click="sendCode"
              :disabled="isCountingDown || !form.email"  
              :loading="sendingCode"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : '获取验证码' }}
            </el-button>
          </el-form-item>
        </div>
        
        <el-form-item label="验证码" prop="code">
          <el-input 
            v-model="form.code"  
            placeholder="请输入6位验证码"
            maxlength="6"
            prefix-icon="Key"
            clearable 
          />
        </el-form-item>
 
        <el-form-item prop="agreed">
    <el-checkbox v-model="uiState.agreed"> 
      我已阅读并同意<el-link type="primary" @click="showAgreement">《用户协议》</el-link>
    </el-checkbox>
  </el-form-item>
 
        <div class="action-buttons">
          <el-button @click="prevStep" class="prev-btn">
            上一步 
          </el-button>
          <el-button 
            type="primary"
            @click="onSubmit"
            :loading="loading"
            class="register-btn"
          >
            立即注册 
          </el-button>
        </div>
      </el-form>
 
      <div class="register-footer">
        <router-link to="/clogin" class="footer-link">
          已有账号？立即登录
        </router-link>
      </div>
    </div>
  </div>
</template>
 
<script>
import { customer_registerAPI, email_sendcodeAPI } from '@/api/api.js';  
import { ElMessage, ElMessageBox } from 'element-plus';
import { User, Lock, Iphone, House, Location, Message, Key } from '@element-plus/icons-vue';
import Agreement from '@/components/utils/Agreement.vue';  
 
export default {
  data() {
    return {
      activeStep: 1,
      form: {
        name: "",
        phone: "",
        email: "",
        code: "",
        company: "",
        password: "",
        address: "",
        agreement_version: ""
      },
      uiState: {
        agreed: false,
        confirmPassword: ""
      },
      loading: false,
      sendingCode: false,
      countdown: 0,
      emailType: "code",
      step1Rules: {
        name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
        ],
        company: [{ required: true, message: '请输入公司名称', trigger: 'blur' }],
        address: [{ required: true, message: '请输入送货地址', trigger: 'blur' }]
      },
      step2Rules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ],
        'uiState.confirmPassword':  [
          { 
            validator: (rule, value, callback) => {
              if (value !== this.form.password)  {
                callback(new Error('两次输入密码不一致!'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { 
            pattern: /^\w+@\w+\.\w+$/,
            message: '请输入有效的邮箱地址', 
            trigger: ['blur', 'change']
          }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '验证码必须为6位数字', trigger: 'blur' }
        ],
        'uiState.agreed':  [
          { 
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('请先同意用户协议'));
              } else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      }
    };
  },
  computed: {
    isCountingDown() {
      return this.countdown  > 0;
    }
  },
  components: { User, Lock, Iphone, House, Location, Message, Key, Agreement },
  mounted() {
    this.$nextTick(() => {
      this.showAgreement(); 
    });
  },
  methods: {
    showAgreement() {
      this.$refs.agreementModal.show(); 
    },
    async nextStep() {
      try {
        await this.$refs.step1Form.validate(); 
        this.activeStep  = 2;
      } catch (error) {
        console.log(' 表单验证失败:', error);
      }
    },
    
    prevStep() {
      this.activeStep  = 1;
    },
 
    async sendCode() {
      try {
        await this.$refs.step2Form.validateField('email');  
        
        this.sendingCode  = true;
        const res = await email_sendcodeAPI({
          email: this.form.email.trim(),  
          type: this.emailType  
        });
 
        if (res.code  === 200) {
          ElMessage.success(' 验证码已发送');
          this.startCountdown();  
        } else {
          ElMessage.error(res.message  || '验证码发送失败');
        }
      } catch (error) {
        const errorMsg = error.response?.data?.message  || 
                       (error?.fields?.email ? '请输入有效的邮箱地址' : '发送失败');
        ElMessage.error(errorMsg);  
      } finally {
        this.sendingCode  = false;
      }
    },
 
    startCountdown(seconds = 60) {
      this.countdown  = seconds;
      const timer = setInterval(() => {
        if (--this.countdown  <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
 
    onAgree(version, agreedTime) {
      this.uiState.agreed  = true;
      this.form.agreement_version  = version;
      this.form.agreed_time  = new Date(agreedTime).toISOString();
    },
 
    async onSubmit() {
      try {
        await this.$refs.step2Form.validate(); 
        
        this.loading  = true;
        const requestData = {
          ...this.form, 
          confirmPassword: this.uiState.confirmPassword 
        };
 
        const res = await customer_registerAPI(
          requestData,
          { code: this.form.code  }
        );
 
        if (res.code  === 200) {
          ElMessageBox.alert( 
            `注册成功！您的客户ID是: ${res.data}`,  
            '注册成功',
            {
              confirmButtonText: '确定',
              callback: () => this.$router.push('/clogin')  
            }
          );
        } else {
          ElMessage.error(res.message  || "注册失败");
        }
      } catch (error) {
        if (!error?.fields) {
          const errorMsg = error.response?.data?.message  || 
                         (error.message.includes('Network  Error') 
                          ? '网络错误，请检查连接' 
                          : '注册失败，请稍后重试');
          ElMessage.error(errorMsg);  
        }
      } finally {
        this.loading  = false;
      }
    }
  }
};
</script>
 
<style scoped>
/* 保持原有样式不变 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
 
.register-card {
  width: 500px;
  padding: 30px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}
 
.info-row {
  display: flex;
  gap: 15px;
}
 
.info-item {
  flex: 1;
}
 
.email-row {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}
 
.email-input {
  flex: 1;
}
 
.code-btn {
  width: 140px;
}
 
.password-address-row {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}
 
.password-column,
.address-column {
  flex: 1;
}
 
.register-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
}
 
.register-title {
  text-align: center;
  margin-bottom: 15px;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 500;
}
 
.register-form {
  margin-top: 20px;
}
 
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #5a5e66;
  margin-bottom: 8px;
}
 
.register-btn {
  width: 100%;
  height: 44px;
  margin-top: 10px;
  font-size: 16px;
  letter-spacing: 1px;
  background-color: rgba(230, 115, 0, 0.775);
  border: none;
  transition: all 0.3s;
}
 
.register-btn:hover {
  background-color: rgba(255, 162, 0, 0.766);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(230, 115, 0, 0.3);
}
 
.register-footer {
  margin-top: 10px;
  text-align: center;
  font-size: 14px;
}
 
.footer-link {
  color: #606266;
  text-decoration: none;
  transition: color 0.3s;
}
 
:deep(.el-input__wrapper.is-focus)  {
  box-shadow: 0 0 0 1px rgba(100, 99, 99, 0.785) inset !important;
}
 
:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px rgba(139, 137, 136, 0.614) inset !important;
} 
 
.footer-link:hover {
  color: rgba(230, 96, 0, 0.842);
}
 
/* 验证码按钮禁用样式 */
:deep(.el-button.is-disabled)  {
  opacity: 0.7;
  cursor: not-allowed;
}
 
/* 新增的分步样式 */
.custom-steps {
  margin-bottom: 20px;
}
 
.action-buttons {
  display: flex;
  gap: 10px;
}
 
.prev-btn {
  width: 100%;
  height: 44px;
  margin-top: 10px;
  font-size: 16px;
  letter-spacing: 1px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  transition: all 0.3s;
}
 
.prev-btn:hover {
  color: rgba(230, 96, 0, 0.842);
  border-color: rgba(230, 96, 0, 0.842);
}
</style>